<?php

namespace app\api1\controller;
use hg\apidoc\annotation as Apidoc;
class OrderInvoice extends Auth
{
    /**
     * @Apidoc\Title("获取列表")
     */
    public function list()
    {
        $list_rows = input('list_rows', 10, 'intval');
        $data = \app\common\model\OrderInvoice::where('member_id', $this->request->uid)
            ->order('id', 'desc')
            ->paginate($list_rows);
        return success('', $data);
    }


    /**
     * @Apidoc\Title("申请发票")
     * @return \think\response\Json|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $data = input('post.');
        if(!$data['company_name']){
            return error('公司名称不能为空！');
        }
        if(!$data['tax_id']){
            return error('纳税人识别号不能为空！');
        }
        if(!$data['email']){
            return error('邮箱不能为空！');
        }
        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            return error('邮件地址不正确！');
        }     
        if(!$data['related_orders']){
            return error('关联订单不能为空！');
        }
        $all_money = 0;
        foreach ($data['related_orders'] as $order_id){
            $order = \app\common\model\NewOrders::where('id', $order_id)->find();
            if(!$order){
                return error('订单号:' . $order_id.',订单不存在！非法请求!');
            }
            if($order['member_id'] != $this->request->uid){
                return error('订单号:' .$order_id.',订单不属于你，非法请求！');
            }
            if($order['is_payment'] != 1){
                return error('订单号:' .$order_id.',订单未支付，不能开发票！');
            }
            if($order['is_apply_for_invoice'] == 1){
                return error('订单号:' .$order_id.',订单已开发票！');
            }
            $all_money += floatval($order['total_amount']);
        }
        if($all_money != floatval($data['amount_of_money'])){
            return error('开票金额不正确！');
        }
        \app\common\model\NewOrders::where('id', 'in', $data['related_orders'])->update(['is_apply_for_invoice' => 1]);
        $data['related_orders'] = implode(',', $data['related_orders']);
        $data['member_id'] = $this->request->uid;
        $data['is_invoicing'] = 0;
        \app\common\model\OrderInvoice::create($data);
        return success('申请成功！');
    }
}